import json

from django.shortcuts import render
from django.views import View
from django import http
from book.models import BookInfo
from book.serializers import BookInfoSerializer
# Create your views here.
class BooksView(View):

    def post(self,request):
        # 保存图书
        # 1.获取前端数据
        data = request.body.decode()
        data_dict =json.loads(data)
        #反序列化的验证步骤
        # 1-生成序列化器类对象，在初始化时将验证的字典参数数据传递给data
        ser = BookInfoSerializer(data=data_dict)
        # 2-调用验证方法
        res = ser.is_valid()
        # 3-验证失败，获取失败的错误信息
        if not res:
            print(ser.errors)
            return http.JsonResponse({'error':ser.errors})
        # 3.保存图书  save()回去调用序列化器中封装的creat方法进行数据库保存
        ser.save()

        #  2.提取对象序列化后的数据
        data = ser.data
        return http.JsonResponse(data)

    def get(self,request):
        """
        获取所有图书
        :param request:
        :return:
        """

        # 1.查询数据库获取所有图书
        books = BookInfo.objects.all()

        # 3. 返回结果
        # 多个模型类对象序列化返回
        # 导入序列化器类，生成序列化器类对象,在初始化时将获取到的模型类对象当成参数传入序列化器类中，传入的参数中，需要增加一个many=True
        ser = BookInfoSerializer(books,many=True)
        book_list = ser.data
        return http.JsonResponse({
            'book_list':book_list
        })



class BookView(View):
    def get(self,request,pk):
        """
        获取单一图书
        :param request:
        :return:
        """
        # 1.根据id值查询数据库
        try:
            book = BookInfo.objects.get(id=pk,is_delete=False)
        except:
            return http.JsonResponse({
                'error':'id不存在'
            },status=400)
        # 2.返回数据
        return http.JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment
        })


    def put(self,request,pk):
        """
        更新图书
        :param request:
        :return:
        """
        # 1.获取前端数据
        data =request.body.decode()
        data_dict = json.loads(data)
        # 验证数据    更新数据时，序列化器初始化除了传递验证的字典数据外，还需要传递更新的数据对象
        book = BookInfo.objects.get(id=pk)
        ser = BookInfoSerializer(book,data=data_dict)
        try:
            ser.is_valid(raise_exception=True)
        except:
            return http.JsonResponse({'error':ser.errors})
        ser.save()
        return http.JsonResponse(ser.data)

    def delete(self,request,pk):
        """
        删除图书
        :param request:
        :return:
        """

        # 1.根据id值查询数据库
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return http.JsonResponse({
                'error': 'id不存在'
            }, status=400)
        # 2.删除图书。逻辑删除、物理删除    book.delete()
        book.is_delete = True
        book.save()

        return http.JsonResponse({'res':'删除成功'})